package com.example.demotest.service.impl;

import com.example.demotest.mapper.PersonMapper;
import com.example.demotest.service.PersonService;
import com.example.demotest.utils.SystemUtil;
import com.example.demotest.config.Result;
import com.example.demotest.config.ResultCode;
import com.example.demotest.pojo.Person;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xiaoxia
 * @version 1.0
 */
@Service
@Slf4j
@SuppressWarnings("all")
public class PersonServiceImpl implements PersonService {
    @Resource
    private PersonMapper personMapper;
    @Override
    public Result getAllPersons(Integer limit,Integer page) {
        Page<Person> objects = PageHelper.startPage(page,limit);
        List<Person> persons = personMapper.getAllPersons();
        Result result = new Result(ResultCode.SUCCESS, objects.getResult());
        result.setCount((int) objects.getTotal());
        return result;
    }

    @Override
    public Boolean deleteOne(Long id) {
        int i = personMapper.deleteOne(id);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    public Boolean updateOrInsert(Person person) {
        int updateOrInsert = 0;
        if (person.getId() != null) {
            //修改
            updateOrInsert = personMapper.update(person);
        }else {
            //新增
            String randomId = SystemUtil.getRandomNumberByNum(2);
            Person person1 = new Person();
            person1.setId(Long.valueOf(randomId));
            person1.setName(person.getName());
            person1.setAge(person.getAge());
            person1.setAddress(person.getAddress());
            updateOrInsert = personMapper.insert(person1);
        }
        if (updateOrInsert > 0){
            return true;
        }
        return false;
    }

    @Override
    public Result selectByTiaoJian(String name, String address , Integer limit, Integer page) {
//        PageHelper helper = new PageHelper();
        Page<Person> objects = PageHelper.startPage(page,limit);
        List<Person> personList = personMapper.selectByTiaoJian(name, address);
        log.info(personList.toString());
        Result result = new Result(ResultCode.SUCCESS, objects.getResult());
        result.setCount((int) objects.getTotal());
        return result;
    }

    @Override
    public Result getAllPersonsTest() {
        List<Person> persons = personMapper.getAllPersons();
        Result result = new Result(ResultCode.SUCCESS, persons);
        log.info(result.toString());
        return result;
    }

}
